package cn.nawang.ebeim.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import cn.nawang.ebeim.client.bean.DownloadProcessBarBean;
import cn.nawang.ebeim.client.bean.FileBean;
import cn.nawang.ebeim.client.bean.RecoveryQueue;
import cn.nawang.ebeim.client.bean.RecoveryTask;
import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.version.Node;
import cn.nawang.ebeim.client.version.VersionTree;
import cn.nawang.ebeim.client.version.VersionTreeUtil;

public class RecoveryThread implements Runnable {
  private static final Logger LOG = LoggerFactory.getLogger(RecoveryThread.class);

  @Override
  public void run() {
    LOG.info("start recovery at {}", System.currentTimeMillis());
    while (!AppMain.stopFlag.get()) {
      RecoveryTask task;
      try {
        task = RecoveryQueue.dequeue();
        boolean result = recovery(task);
        if(result){
          DbUtil.updateRecoveryTask(task.getId(), DbUtil.STATUS_FINISHED);
        }else{
          LOG.info("更改数据库下载失败"+new Gson().toJson(task));
          DbUtil.updateRecoveryTask(task.getId(), DbUtil.STATUS_ERROR);
        }
        /** 记录任务操作日志 */
        saveOperationLog(task);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public boolean recovery(RecoveryTask task) {
    VersionTree vt = VersionTreeUtil.getVersionTree(task.getDataSourceId(), task.getVersion());
    if (vt == null) {
      LOG.info("找不到版本树");
      return false;
    }

    String lastChar = task.getPath().substring(task.getPath().length()-1, task.getPath().length());
    Node node = null;
    if(task.getPath().equals("/")||lastChar.equals("/")){
      node = vt.getRoot();
    }else{
      node = vt.findNode(task.getPath());
    }
    
    if (node != null) {
      
      FileBean fileBean = CommonMethodsUtils.recoveryFilesize(node);
      DownloadProcessBarBean exist = DbUpDownloadUtil.getDownloadProcessBarByNid(DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS, task.getNid());
      if(exist!=null){
        DbUpDownloadUtil.deleteDownloadProcessBarByNid(task.getNid());
      }
      DownloadProcessBarBean bean = new DownloadProcessBarBean();
      bean.setDsId(task.getDataSourceId());
      bean.setTotal(fileBean.getFileSize());
      bean.setFileSum(fileBean.getFileSum());
      bean.setCount(0l);
      bean.setNid(task.getNid());
      bean.setStatus(DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING);
      DbUpDownloadUtil.addDownloadProcessBar(bean);
      
      return node.traverse(new FileRecoveryOp(task));
    }
    LOG.info("找不到节点");
    return false;
  }

  public void saveOperationLog(RecoveryTask task) {
    LOG.debug("TODO - saveOperationLog");
  }

}
